import { createRouter, createWebHashHistory } from "vue-router";
import type { RouteRecordRaw } from "vue-router";
import type { App } from "vue";
import Cookies from "js-cookie";
import { useAdminStatewithout } from "@/store/modules/adminUser";
import * as http from "@/request/api";

const routes: RouteRecordRaw[] = [
  {
    path: "/login",
    name: "login",
    component: () => import("../views/login/Login.vue"),
  },
];

const router = createRouter({
  history: createWebHashHistory(),
  routes,
});
// 全局导航守卫
router.beforeEach(async (to, from, next) => {
  // 判断token 存在时 有没有 menus
  const token = Cookies.get("token");
  const useStore = useAdminStatewithout();
  const menu = useStore.menus;
  let useStoreMenus = useStore.getMenusList;
  // 生成crumber
  let newArr = to.path.split("/").filter((item) => item);
  if (useStoreMenus) {
    for (let key in useStoreMenus) {
      if (useStoreMenus[key].name === newArr[0]) {
        useStore.crumber.second = useStoreMenus[key].title;
        useStoreMenus[key].children?.forEach((el) => {
          if (el.name === newArr[1]) {
            useStore.crumber.third = el.title;
          }
        });
      }
    }
  }
  if (token && menu.length === 0) {
    let userInfo = await http.admin.AdminInfo();
    if (userInfo.code === 200) {
      useStore.updateMenus(userInfo.data.menus);

      // 生成动态路由
      let useStoreMenus = useStore.getMenusList;
      for (let key in useStoreMenus) {
        let childRouter: RouteRecordRaw = {
          path: "/" + useStoreMenus[key].name,
          name: useStoreMenus[key].name,
          component: () => import(`@/views/home/Home.vue`),
          children: [],
        };
        useStoreMenus[key].children?.forEach((item) => {
          // hasOwnProperty:判断属性是否是自身的属性
          childRouter.children?.push({
            name: item.name,
            path: item.name,
            component: () =>
              import(
                `@/views/${useStoreMenus[key].name}/${item.name}/${item.name}.vue`
              ),
          });
        });
        router.addRoute(childRouter);
      }
      router.addRoute({
        path: "/",
        name: "home",
        redirect: "/index",
        component: () => import("@/views/home/Home.vue"),
        children: [
          {
            path: "index",
            name: "index",
            component: () => import("@/views/index/index.vue"),
          },
        ],
      });

      // console.log(useStore.crumber);

      return next(to.fullPath);
    } else {
      Cookies.remove("token");
      return next("/login");
    }
  } else if (!token && to.path !== "/login") {
    return next("/login");
  } else if (token && to.path === "/login") {
    return next(from);
  } else {
    next();
  }
});

// 初始化方法
export const initRouter = (app: App<Element>) => {
  app.use(router);
};
